package com.ben.multiple.fdfs;

import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
@Slf4j
public class FdfsResource {
    private final FastDfsClient fastDfsClient;

    public FdfsResource(FastDfsClient fastDfsClient) {
        this.fastDfsClient = fastDfsClient;
    }

    @GetMapping("/download")
    public void download(@RequestParam(value = "filePath") String filePath, HttpServletResponse response) {
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            fastDfsClient.downloadFile(filePath, outputStream);
            log.info("download file success: {}", filePath);
        } catch (IOException e) {
            log.error("download file error : ", e);
            throw new RuntimeException("download file error");
        }
    }

    @PostMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        String path = fastDfsClient.uploadFile(file);
        log.info("upload file success: {}", path);
        return ResponseEntity.ok().body(path);
    }

    @DeleteMapping("/delete")
    public ResponseEntity<Boolean> delete(@RequestParam(value = "filePath") String filePath) {
        fastDfsClient.deleteFile(filePath);
        log.info("delete file success: {}", filePath);
        return ResponseEntity.ok(true);
    }
}
